package com.yuantu.judiciary.config;

import com.yuantu.judiciary.model.domain.InviteRecordDO;
import com.yuantu.judiciary.model.dto.AccountInfoDTO;
import com.yuantu.judiciary.model.enums.InviteCodeType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.lang.reflect.Field;
import java.sql.Timestamp;

/**
 * jpa 自动添加 创建人/创建时间/修改人/修改时间 配置
 *
 * @author syw
 * @since 2023-06-07
 **/
@Component
@Slf4j
public class DataBaseAuditListener {

    /**
     * 被@Prepersist注解的方法 ，完成save之前的操作。
     *
     * @param object .
     */
    @PrePersist
    public void prePersist(Object object) throws IllegalArgumentException, IllegalAccessException {
        Class<?> aClass = object.getClass().getSuperclass();

        try {
            Field createdBy = aClass.getDeclaredField("creatorId");
            createdBy.setAccessible(true);
            Object createdByValue = createdBy.get(object);
            if (createdByValue == null) {
                createdBy.set(object, getCurrentAccountId());
            }
            Field createdTime = aClass.getDeclaredField("createTime");
            createdTime.setAccessible(true);
            Object createdTimeValue = createdTime.get(object);
            if (createdTimeValue == null) {
                createdTime.set(object, new Timestamp(System.currentTimeMillis()));
            }
        } catch (NoSuchFieldException e) {
            log.error("反射获取属性异常：", e);
        }
    }

    /**
     * 被@Preupdate注解的方法 ，完成update之前的操作。
     *
     * @param object .
     */
    @PreUpdate
    public void PreUpdate(Object object) throws IllegalArgumentException, IllegalAccessException {
        Class<?> aClass = object.getClass().getSuperclass();

        try {
            Field updatedBy = aClass.getDeclaredField("modifierId");
            updatedBy.setAccessible(true);
            updatedBy.set(object, getCurrentAccountId());

            Field updatedTime = aClass.getDeclaredField("modifyTime");
            updatedTime.setAccessible(true);
            updatedTime.set(object, new Timestamp(System.currentTimeMillis()));
        } catch (NoSuchFieldException e) {
            log.error("反射获取属性异常：", e);
        }
    }

    /**
     * 被@Postpersist注解的方法 ，完成save之后的操作。
     *
     * @param object .
     */
    @PostPersist
    public void postPersist(Object object) throws IllegalArgumentException, IllegalAccessException {
    }

    /**
     * 被@Postupdate注解的方法 ，完成update之后的操作。
     *
     * @param object .
     */
    @PostUpdate
    public void postUpdate(Object object) throws IllegalArgumentException, IllegalAccessException {
    }

    /**
     * 获取当前账号 id
     */
    public Long getCurrentAccountId() {
        try {
            if (ObjectUtils.isEmpty(SecurityContextHolder.getContext())
                    || ObjectUtils.isEmpty(SecurityContextHolder.getContext().getAuthentication())
                    || ObjectUtils.isEmpty(SecurityContextHolder.getContext().getAuthentication().getPrincipal())
            ) {
                return null;
            } else {
                AccountInfoDTO accountInfo = (AccountInfoDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                return accountInfo.getAccountId();
            }
        } catch (Exception e) {
//            log.error("获取当前账号 id 失败: " + e.getMessage(), e);
        }
        return null;
    }

}
